//
//  ChooseCarController.m
//  chooseBrand
//
//  Created by 祥云创想 on 16/7/5.
//  Copyright © 2016年 Lee. All rights reserved.
//

#import "ChooseCarController.h"
#import "CarHeadView.h"
#import "CarCell.h"
#import "HotCarCell.h"
#import "HotCarHeadView.h"
#import "UIView+LXExtension.h"
#import "CXBCarBrandContentModel.h"
#import "SeriesCarCell.h"
#import "CXBCarInfoViewModel.h"
#import "CXBCarBrandModel.h"
#import "InnerCarCell.h"
#import "CXByuyueThirdContentModel.h"
#import "CXBRepareThirdCell.h"

#import "CXBHotCarBrand.h"

#define KeyWindow  [UIApplication sharedApplication].keyWindow
// 头部Cell的高度
static float HeadCellHeight = 110;
// 其它Cell的高度
static float OtherCellHeight = 50;
// HeaderView的高度
static float HeaderViewHeight = 30;

static float HotViewHeight = 49;
static NSString *HotCellIdentifier = @"HotCellIdentifier";
static NSString *OtherCellIdentifier = @"OtherCellIdentifier";

static NSString *NextCellIdentifier = @"NextCellIdentifier";
static NSString *SeriesCarCellIdentifier = @"SeriesCarCellIdentifier";
static NSString *InnerCarCellIdentifier = @"InnerCarCellIdentifier";
@interface ChooseCarController ()<UIGestureRecognizerDelegate,HotCarCellDelegate>
/**
 *  品牌型号数组
 */
@property (nonatomic, strong) NSMutableArray *brandSourceArr;
/**
 *  热门品牌型号数组
 */
@property (nonatomic, strong) NSMutableArray *hotBrandSourceArr;
/**
 *  品牌系列数组
 */
@property (nonatomic, strong) NSMutableArray *seriesSourceArr;
/**
 *  侧滑tableView
 */
@property (nonatomic, strong) UITableView *nextTavleView;

@property (nonatomic, strong) UITableView *secondTavleView;

@property (nonatomic, strong) UIView *bgView;

@property (nonatomic, strong) UIView *twoBgView;

@property (nonatomic,strong) UITableView *twoInneriTableView;

@property (nonatomic, strong) CXBCarBrandContentModel *selecterModel;

@property (nonatomic, strong) SeriesCarCell *nextSelecterCell;

@property (nonatomic, strong) InnerCarCell *innerSelecterCell;

@property (nonatomic, strong) NSMutableArray *indexTitleArr;
@property (nonatomic, strong) NSMutableArray *allArr;
@property (nonatomic, strong) NSArray *thirdArr;
@property (nonatomic, strong) CXBNoInterNetView *noNetView;

@end

@implementation ChooseCarController
-(CXBNoInterNetView *)noNetView
{
    if (_noNetView == nil) {
        _noNetView = [[CXBNoInterNetView alloc] init];
    }
    return _noNetView;
    
}

-(NSArray *)thirdArr
{
    if (_thirdArr == nil) {
        _thirdArr = [NSArray array];
    }
    return _thirdArr;
    
}
-(NSMutableArray *)allArr
{
    if (_allArr == nil) {
        _allArr = [NSMutableArray array];
    }
    return _allArr;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    [self baseSetup];
    [self netWork];
//    MJChiBaoZiHeader *header = [MJChiBaoZiHeader headerWithRefreshingTarget:self refreshingAction:@selector(initData)];
    MJRefreshNormalHeader *header=[MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self initData];
        
    }];
    //已经处理无网络
    self.tableView.mj_header= header;

    [self.tableView.mj_header beginRefreshing];
}
-(void)initData
{
    //获取全部
            [self loadMainData];
            [self.tableView.mj_footer  resetNoMoreData];
    
}

-(void)loadMainData
{
    WEAKSELF
    [[CXBCarInfoViewModel shareInfoModel] searchCarBrandInfoWithPID:@"0" andHierarchy:@"2" Success:^(NSDictionary *result) {
        if ([result[@"code"]integerValue] == 1) {
            DLog(@"reslut=%@",result);
                self.allArr=nil;
            [self.noNetView removeFromSuperview];
            NSArray *ResultJsonArr = [WHJSON objectFormJsonString:result[@"ResultJson"]];
            NSMutableArray *mutableArr=[NSMutableArray array];
            for (NSDictionary *dic in ResultJsonArr) {
                CXBCarBrandContentModel *model=[CXBCarBrandContentModel mj_objectWithKeyValues:dic];
                [mutableArr addObject:model];
                
            }
            self.brandSourceArr=mutableArr;
            [self.indexTitleArr enumerateObjectsUsingBlock:^(NSString *   Titleobj, NSUInteger idx, BOOL * _Nonnull stop) {
                NSMutableArray *array = [NSMutableArray array];
                [self.brandSourceArr enumerateObjectsUsingBlock:^(CXBCarBrandContentModel *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    if ([Titleobj isEqualToString:obj.FirstLetter] ) {
                        [array addObject:obj];
                        
                    }
                    
                }];
                [self.allArr addObject:array];
                
            }];
            [self.tableView reloadData];
            
            [self.tableView.mj_header endRefreshing];
            
        }
    } andfailure:^{
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];

        [self.view addSubview:self.noNetView];
        
        self.noNetView.frame=CGRectMake(0, 0, WHIDTH, HEIGHT);
        self.noNetView.backBlock=^{
            
       #warning 注意是否需要POP到前一个界面
             [weakSelf.navigationController popViewControllerAnimated:YES];
            
        };
        WEAKSELF
        self.noNetView.reloadBlock=^{
            
            
            [weakSelf.tableView.mj_header beginRefreshing];
    
        };

        
    }];
//    
    //热门品牌
    [[CXBCarInfoViewModel shareInfoModel] searchHotCarBrandListSuccess:^(NSDictionary *result) {
      
        NSArray *ResultJsonArr = [WHJSON objectFormJsonString:result[@"ResultJson"]];
        NSMutableArray *mutableArr=[NSMutableArray array];
        for (NSDictionary *dic in ResultJsonArr) {
            CXBHotCarBrand *model=[CXBHotCarBrand mj_objectWithKeyValues:dic];
            [mutableArr addObject:model];
            
        }
        self.hotBrandSourceArr=mutableArr;
               [self.tableView reloadData];
    
    }];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [UIView animateWithDuration:0.2 animations:^{
        self.bgView.alpha = 1;
    }];
    
}

- (void)netWork
{
    
}

- (void)getCarModelDataWithModel:(CXBCarBrandContentModel *)model
{
    [self.seriesSourceArr removeAllObjects];
    [self.nextTavleView reloadData];
    
}


- (void)baseSetup
{
    self.navigationItem.title = @"请选择品牌";
    
    self.tableView.sectionIndexColor = [UIColor grayColor];
//    self.tableView.sectionIndexBackgroundColor = [UIColor clearColor];
    self.navigationController.navigationBar.alpha=1;
    self.navigationController.navigationBar.backgroundColor=[UIColor whiteColor];
    
    //注册
    [self.tableView registerClass:[CarCell class] forCellReuseIdentifier:OtherCellIdentifier];
    [self.tableView registerClass:[HotCarCell class] forCellReuseIdentifier:HotCellIdentifier];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    //添加侧滑视图
    [KeyWindow addSubview:self.bgView];
  
}

#pragma mark -dataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    //
    if (tableView.tag == 99) {
        return 1;
    }
    //测试数据
    return self.allArr.count+1 ;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    if (tableView==self.secondTavleView) {
        return self.thirdArr.count;
    }
    if (tableView == self.nextTavleView) {
        return self.seriesSourceArr.count;
    }
    
    if (tableView==self.tableView) {
        if (section == 0) {
            return 1;
        }
        NSArray *arr=self.allArr[section-1];
        return arr.count;
    }
    
    return 0;
}

#pragma mark -tableViewDelegate
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == 99) {
        if (tableView==self.nextTavleView) {
            SeriesCarCell *cell = [tableView dequeueReusableCellWithIdentifier:SeriesCarCellIdentifier];
            //测试数据 取消模型传递
            cell.carBrandModel = self.seriesSourceArr[indexPath.row];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
        else if(tableView==self.secondTavleView)
        {
            CXBRepareThirdCell *cell = [tableView dequeueReusableCellWithIdentifier:@"thrid"];
            //测试数据 取消模型传递
            cell.carBrandModel = self.thirdArr[indexPath.row];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
        
        
    }
    
    if (indexPath.section == 0 &&indexPath.row == 0) {
        HotCarCell *cell = [tableView dequeueReusableCellWithIdentifier:HotCellIdentifier];
        
        //测试数据 取消模型传递
                if (self.hotBrandSourceArr.count) {
                    cell.CarModelArr = self.hotBrandSourceArr;
                }
        cell.delegate = self;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    if (tableView==self.tableView) {
        CarCell *cell = [tableView dequeueReusableCellWithIdentifier:OtherCellIdentifier];
        cell.CarModel = self.allArr[indexPath.section-1][indexPath.row];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (tableView==self.tableView) {
        if (section == 0 ) {
            return HotViewHeight;
        }
        return HeaderViewHeight;
    }
    else
    {
        return 0;
        
    }
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (tableView==self.tableView) {
        if (section == 0) {
            
            HotCarHeadView *headView = [[HotCarHeadView alloc] initWithFrame:CGRectMake(0, 0, 0, HeaderViewHeight)];
            if (tableView.tag == 99) {
                
                headView.CarModel = self.selecterModel;
                
                return headView;
            }
            return headView;
        }
        
        CarHeadView *headView = [[CarHeadView alloc] initWithFrame:CGRectMake(0, 0, 0, HeaderViewHeight)];
        
        headView.nameLable = self.indexTitleArr[section-1];
        return headView;
    }
    
    return nil;
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == 99) {
        return OtherCellHeight;
    }
    
    if (indexPath.section == 0 &&indexPath.row == 0) {
        return HeadCellHeight;
    }
    return OtherCellHeight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    DLog(@"点击");
    if (tableView==self.tableView) {
        CXBCarBrandContentModel *model=self.allArr[indexPath.section-1][indexPath.row];
        //保存第一层模型
        [CXBSignalModel shareSignalModel].firstModel=model;
        
         [self.noNetView bringSubviewToFront:KeyWindow];
        DLog(@"indexPath=%@",indexPath);
        [[CXBCarInfoViewModel shareInfoModel]searchCarBrandInfoWithPID:model.ID andHierarchy:@"3" Success:^(NSDictionary *result) {
            
            DLog(@"reslut=%@",model.PID);
            NSArray *ResultJsonArr = [WHJSON objectFormJsonString:result[@"ResultJson"]];
            DLog(@"ResultJsonArr=%@",ResultJsonArr);
            NSMutableArray *mutableArr=[NSMutableArray array];
            for (NSDictionary *dic in ResultJsonArr) {
                CXBCarBrandContentModel *model=[CXBCarBrandContentModel mj_objectWithKeyValues:dic];
                [mutableArr addObject:model];
                
            }
            self.seriesSourceArr=mutableArr;
            [self.nextTavleView reloadData];
        } andfailure:^{
            [self.tableView reloadData];  
        }];
        
        
    }
    if (tableView.tag == 99) {
        if (tableView==self.secondTavleView) {
            DLog(@"点击了");
            CXByuyueThirdContentModel *model=self.thirdArr[indexPath.row];
            //型号ID
            [NSKeyedArchiver archiveRootObject:model toFile:HMCarPath];
            //发送通知   选择了新的车辆
            [[NSNotificationCenter defaultCenter] postNotificationName:@"newCar" object:nil];
//           //类型名称
            [HMSaveDataTool setValue:model.TypeName forKey:@"TypeName"];

            [self.bgView removeFromSuperview];
            [self.twoBgView removeFromSuperview];
            [self.navigationController popViewControllerAnimated:YES];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"MyCarRefreash" object:nil];
            
               [self.noNetView bringSubviewToFront:KeyWindow];
        }
        else{
            [UIView animateWithDuration:0.23 animations:^{
                
            }completion:^(BOOL finished) {
                
                [KeyWindow addSubview:self.twoBgView];
                [self animation:self.twoBgView];
                     [self.noNetView bringSubviewToFront:KeyWindow];
                CXBCarBrandContentModel *model=self.seriesSourceArr[indexPath.row];
                DLog(@"indexPath=%@",indexPath);
                [[CXBCarInfoViewModel shareInfoModel]searchCarTypeListWithModelId:model.ID andtypeSeries:@"" Success:^(NSDictionary *result) {
                    DLog(@"reslut=%@",result);
                    NSArray *ResultJsonArr = [WHJSON objectFormJsonString:result[@"ResultJson"]];
                    NSMutableArray *mutableArr=[NSMutableArray array];
                    for (NSDictionary *dic in ResultJsonArr) {
                        CXByuyueThirdContentModel *model=[CXByuyueThirdContentModel mj_objectWithKeyValues:dic];
                        [mutableArr addObject:model];
                    }
                    self.thirdArr=mutableArr;
                    [self.secondTavleView reloadData];
                    
                }];
            }];
            
        }
        return ;
    }
    [self getCarModelDataWithModel:self.selecterModel];
    [self animation:self.bgView];
}



#pragma mark -IndexTitles
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    if (tableView.tag == 99) {
        return nil;
    }
    return self.indexTitleArr;
}

#pragma mark -UIGestureRecognizerDelegate
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {//如果当前是tableView
        //做自己想做的事
        return NO;
    }
    return YES;
    
}

#pragma mark -热门品牌

-(void)tableViewCell:(HotCarCell *)tableViewCell didSelectBtnWithCarModel:(CXBCarBrandContentModel *)CarModel
{
#warning 车辆
    self.selecterModel = CarModel;

        //保存第一层模型
        [CXBSignalModel shareSignalModel].firstModel=self.selecterModel;
        
        [self.noNetView bringSubviewToFront:KeyWindow];
    
        [[CXBCarInfoViewModel shareInfoModel]searchCarBrandInfoWithPID:CarModel.ID andHierarchy:@"3" Success:^(NSDictionary *result) {
            
         
            NSArray *ResultJsonArr = [WHJSON objectFormJsonString:result[@"ResultJson"]];
     
            NSMutableArray *mutableArr=[NSMutableArray array];
            for (NSDictionary *dic in ResultJsonArr) {
                CXBCarBrandContentModel *model=[CXBCarBrandContentModel mj_objectWithKeyValues:dic];
                [mutableArr addObject:model];
                
            }
            self.seriesSourceArr=mutableArr;
            [self.nextTavleView reloadData];
        } andfailure:^{
            [self.tableView reloadData];
        }];
    [self getCarModelDataWithModel:self.selecterModel];
    [self animation:self.bgView];
}
#pragma mark - get  set  mothed
- (NSMutableArray *)indexTitleArr
{
    if (!_indexTitleArr) {
        _indexTitleArr = [NSMutableArray array];
        NSArray *arr = @[@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z"];
        [_indexTitleArr addObjectsFromArray:arr];
    }
    return _indexTitleArr;
}
- (NSMutableArray *)hotBrandSourceArr
{
    if (!_hotBrandSourceArr) {
        _hotBrandSourceArr = [NSMutableArray array];
        
    }
    return _hotBrandSourceArr;
}

- (NSMutableArray *)brandSourceArr
{
    if (!_brandSourceArr) {
        _brandSourceArr = [NSMutableArray array];
    }
    return _brandSourceArr;
}

- (NSMutableArray *)seriesSourceArr
{
    if (!_seriesSourceArr) {
        _seriesSourceArr = [NSMutableArray array];
    }
    return _seriesSourceArr;
}

- (UIView *)bgView
{
    if (!_bgView) {
        _bgView = [UIView new];
        _bgView.frame = self.view.frame;
        _bgView.lx_x = self.view.lx_width;
        _bgView.lx_y = 64;
        _bgView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.3];
        
        [self.bgView addSubview:self.nextTavleView];
        
        //添加手势
        UITapGestureRecognizer *tag = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectClick)];
        tag.delegate = self;
        [_bgView addGestureRecognizer:tag];
        //设置子控件位置
        self.nextTavleView.lx_x = 100;
        self.nextTavleView.lx_y = 0;
        self.nextTavleView.lx_width = self.view.lx_width - 100;
        self.nextTavleView.lx_height = self.view.lx_height;
        
        
    }
    return _bgView;
}

-(UIView *)twoBgView{
    if (!_twoBgView) {
        _twoBgView = [UIView new];
        _twoBgView.frame = self.view.frame;
        _twoBgView.lx_x = self.view.lx_width;
        _twoBgView.lx_y = 64;
        _twoBgView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.3];
        
        [_twoBgView addSubview:self.secondTavleView];
        ;
        //添加手势
        UITapGestureRecognizer *tag = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectClick1)];
        tag.delegate = self;
        [_twoBgView addGestureRecognizer:tag];
        
        //设置子控件位置
        self.secondTavleView.lx_x = 100;
        self.secondTavleView.lx_y = 0;
        self.secondTavleView.lx_width = self.view.lx_width - 100;
        self.secondTavleView.lx_height = self.view.lx_height;
        self.secondTavleView.backgroundColor = [UIColor whiteColor];
    }
    return _twoBgView;
}


-(UITableView *)secondTavleView
{
    if (!_secondTavleView) {
        _secondTavleView = [[UITableView alloc] init];
        _secondTavleView.tag = 99;
        _secondTavleView.dataSource = self;
        _secondTavleView.delegate = self;
        _secondTavleView.tableFooterView = [UIView new];
        _secondTavleView.contentInset = UIEdgeInsetsMake(0, 0, 64, 0);
        _secondTavleView.separatorStyle = NO;
        _secondTavleView.backgroundColor = [UIColor whiteColor];
        [_secondTavleView registerClass:[CXBRepareThirdCell class] forCellReuseIdentifier:@"thrid"];
    }
    return _secondTavleView;
}


- (UITableView *)nextTavleView
{
    if (!_nextTavleView) {
        _nextTavleView = [[UITableView alloc] init];
        _nextTavleView.tag = 99;
        _nextTavleView.dataSource = self;
        _nextTavleView.delegate = self;
        _nextTavleView.tableFooterView = [UIView new];
        _nextTavleView.contentInset = UIEdgeInsetsMake(0, 0, 64, 0);
        
        _nextTavleView.separatorStyle = NO;
        _nextTavleView.backgroundColor = [UIColor whiteColor];
        [_nextTavleView registerClass:[SeriesCarCell class] forCellReuseIdentifier:SeriesCarCellIdentifier];
    }
    return _nextTavleView;
}

#pragma mark - other
- (void)animation:(UIView *)view
{
    
    [UIView animateWithDuration:0.5 delay:0 usingSpringWithDamping:1 initialSpringVelocity:8 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        view.lx_x = 0;
    } completion:^(BOOL finished) {
        
    }];
}

#pragma mark -手势
- (void)selectClick
{
    [UIView animateWithDuration:0.5 delay:0 usingSpringWithDamping:1 initialSpringVelocity:8 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        self.bgView.lx_x = self.view.lx_width;
        self.twoBgView.lx_x = self.view.lx_width;
    } completion:^(BOOL finished) {
        DLog(@"11111");
        self.selecterModel = nil;
        self.nextSelecterCell.selecterImage.hidden = YES;
        [self.nextTavleView reloadData];
    }];
}

-(void)selectClick1
{
    [UIView animateWithDuration:0.5 delay:0 usingSpringWithDamping:1 initialSpringVelocity:8 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        self.twoBgView.lx_x = self.view.lx_width;
    } completion:^(BOOL finished) {
        
        
    }];
}
#pragma mark----view即将消失
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.bgView removeFromSuperview];
    [self.twoBgView removeFromSuperview];
    
}
- (void)dealloc
{
    [self.bgView removeFromSuperview];
}
@end
